package com.skywolf.chem.utils;

import com.skywolf.chem.usercenter.pojo.vo.PermissionVO;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName PermissionTreeUtils.java
 * @Author Leo
 * @Version 1.0.0
 * @Description 权限 tree
 * @CreateTime 2019年12月02日 23:57:00
 */
public final class PermissionTreeUtils {
    /**
     * 递归构建权限树
     *
     * @param treeNodes
     * @return
     */
    public static List<PermissionVO> buildTreeByRecursive(List<PermissionVO> treeNodes) {
        List<PermissionVO> trees = new ArrayList<>();
        for (PermissionVO treeNode : treeNodes) {
            if (Long.valueOf(0).equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归构建子节点
     *
     * @param treeNodes
     * @return
     */
    public static PermissionVO findChildren(PermissionVO treeNode, List<PermissionVO> treeNodes) {
        treeNode.setChildren(new ArrayList<>());

        for (PermissionVO p : treeNodes) {
            if (treeNode.getId().equals(p.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.getChildren().add(findChildren(p, treeNodes));
            }
        }
        return treeNode;
    }
}
